﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Common;
using Model;

namespace AcceptServer.Service
{
    class PhoneUserProtocol
    {
        OperateDataBase operateDataBase = new OperateDataBase();
        public byte[] PhoneUserRegister(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            List<byte> body = new List<byte>();
            try
            {
                //string asServerip = AcceptMainForm.PositionService.GetFreeAcceptServerIp(AcceptMainForm.ServerWebIp);
                //string asServerip = "221.232.148.74";
                string asServerip = "0.0.0.0";
                //string localServerIp = string.Empty;

                //IniFiles myini = new IniFiles(Environment.CurrentDirectory + "\\system.ini");
                //string analysisIp = myini.ReadString("SERVERCONFIG", "AnalysisIp", "off");
                //if (analysisIp.ToLower().Equals("on"))
                //{
                //    localServerIp = GetLocalServerIP(clientIp.ToString());
                //    if (localServerIp != string.Empty)
                //    {
                //        asServerip = localServerIp;//123
                //    }
                //}

                IPAddress ip = null;
                bool isIpstr = Regex.IsMatch(asServerip, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
                if (isIpstr)
                {
                    ip = IPAddress.Parse(asServerip);
                }
                else
                {
                    IPAddress[] ips = Dns.GetHostAddresses(asServerip);
                    if (ips.Length > 0)
                        ip = ips[0];
                }
                if (ip == null)
                {
                    body.Clear();
                    body.Add(0);
                }
                else
                {
                    body.Add(1);
                    body.AddRange(ip.GetAddressBytes());
                    string phonestr = OperateConfig.GetCenterPhoneNumber();
                    byte[] phoneBcd = CommonRoutine.BcdStringToBytes(phonestr.PadLeft(12, '0'));
                    body.AddRange(phoneBcd);

                    //longitude 
                    string longitudestr = OperateConfig.GetOffSetLongitude();
                    byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                    body.AddRange(longitudeBytes);
                    //latitude 
                    string latitudestr = OperateConfig.GetOffSetLatitude();
                    byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                    body.AddRange(latitudeBytes);

                    //string version = OperateConfig.GetPhoneUserClientVersion();
                    string version = AcceptMainForm.PhoneUserClientVersion;
                    byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                    body.AddRange(vBytes);

                }

                //------------------黑名单               
                string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
                int count = operateDataBase.GetRecordCountOfUserInThisMonth(phoneNumber, 1);
                if (count >= 1)
                {
                    body.Clear();
                    body.Add(1);
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("PhoneUserProtocol.cs-93");
                body.Clear();
                body.Add(0);
            }

            byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdPhoneUserRegisterReply, false, false, body.Count, phoneNumberbyts,
                                                serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());


            //------------------------将手机用户登陆录入数据库
            string phoneNum = OperateAgreement.GetPhoneNumInMessageHead(realData);
            DateTime timeNow = DateTime.Now;
            if (operateDataBase.PhoneuserExists(phoneNum))
            {
                bool isUpdateok =
                operateDataBase.PhoneuserUpdateByNum(phoneNum, 0,
                timeNow.ToString("yyyy-MM-dd HH:mm:ss"));
                if (!isUpdateok)
                    Console.WriteLine("手机客户登陆记录更新失败：" + phoneNum + timeNow);
            }
            else
            {
                PhoneUserInfo phoneUser = new PhoneUserInfo();
                phoneUser.PhoneNumber = phoneNum;
                phoneUser.FirstLoginTime = timeNow.ToString("yyyy-MM-dd HH:mm:ss");
                phoneUser.LastLoginTime = phoneUser.FirstLoginTime;
                phoneUser.LoginCount = 1;
                phoneUser.type = "0";
                if (!operateDataBase.PhoneuserAdd(phoneUser))
                {
                    Console.WriteLine("新手机客户登陆记录添加失败：" + phoneNum + timeNow);
                }
            }

            return tempData;
        }


        public byte[] PhoneUserRegister2(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);


            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
         
            List<byte> body = new List<byte>();
            try
            {

                string asServerip = "0.0.0.0";

                IPAddress ip = null;
                bool isIpstr = Regex.IsMatch(asServerip, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
                if (isIpstr)
                {
                    ip = IPAddress.Parse(asServerip);
                }
                else
                {
                    IPAddress[] ips = Dns.GetHostAddresses(asServerip);
                    if (ips.Length > 0)
                        ip = ips[0];
                }
                if (ip == null)
                {
                    body.Clear();
                    body.Add(0);
                }
                else
                {
                    body.Add(1);
                    body.AddRange(ip.GetAddressBytes());
                    string phonestr = OperateConfig.GetCenterPhoneNumber();
                    byte[] phoneBcd = CommonRoutine.BcdStringToBytes(phonestr.PadLeft(12, '0'));
                    body.AddRange(phoneBcd);

                    //longitude 
                    string longitudestr = OperateConfig.GetOffSetLongitude();
                    byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                    body.AddRange(longitudeBytes);
                    //latitude 
                    string latitudestr = OperateConfig.GetOffSetLatitude();
                    byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                    body.AddRange(latitudeBytes);

                    //string version = OperateConfig.GetPhoneUserClientVersion();
                    string version = AcceptMainForm.PhoneUserClientVersion;
                    byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                    body.AddRange(vBytes);

                }

                //------------------黑名单               
              
                int count = operateDataBase.GetRecordCountOfUserInThisMonth(phoneNumber, 1);
                if (count >= 1)
                {
                    body.Clear();
                    body.Add(1);
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("PhoneUserProtocol.cs-200");
                body.Clear();
                body.Add(0);
            }
            try
            {
                byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdPhoneUserRegisterReply2, false, false, body.Count, phoneNumberbyts,
                                               serialNumber, 0, 0);
                byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
                 
                //0-7  IMEI 8byte
                byte[] IMEI_bytes = new byte[8];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, IMEI_bytes, 0, 8);
                string IMEI = CommonRoutine.ByteToBcdString(IMEI_bytes);
                IMEI = IMEI.Remove(0, 1);

                //8-11  4byte  Version
                byte[] version_bytes = new byte[4];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex + 8, version_bytes, 0, 4);
                Array.Reverse(version_bytes);
                int nowVersion = BitConverter.ToInt32(version_bytes, 0);

                //------------------------将手机用户登陆录入数据库
                string phoneNum = OperateAgreement.GetPhoneNumInMessageHead(realData);
                DateTime timeNow = DateTime.Now;

                PhoneUserInfo model = operateDataBase.PhoneuserGetModelByPhoneNumber(phoneNum);            
                if (model != null)
                {
                    model.LastLoginTime = timeNow.ToString("yyyy-MM-dd HH:mm:ss");
                    model.PhoneVersion = nowVersion.ToString();
                    model.type = "0";
                    model.LoginCount++;
                    //if(string.IsNullOrEmpty(model.PhoneIMEI)
                    //    &&!operateDataBase.PhoneUserImeiExit(IMEI))
                    //{
                    model.PhoneIMEI = IMEI;
                    //}
                    if (!operateDataBase.PhoneuserUpdate(model))
                    {
                        Console.WriteLine("手机客户登陆记录更新失败：" + phoneNum + timeNow);
                    }
                }
                else  //数据库无记录  且imei号未被使用 增加新用户
                {
                    PhoneUserInfo phoneUser = new PhoneUserInfo();
                    phoneUser.PhoneNumber = phoneNum;
                    phoneUser.FirstLoginTime = timeNow.ToString("yyyy-MM-dd HH:mm:ss");
                    phoneUser.LastLoginTime = phoneUser.FirstLoginTime;
                    phoneUser.LoginCount = 1;
                    phoneUser.type = "0";
                    phoneUser.PhoneVersion = nowVersion.ToString();
                    if (!operateDataBase.PhoneUserImeiExit(IMEI))
                    {
                        phoneUser.PhoneIMEI = IMEI;
                        if (!operateDataBase.PhoneuserAdd(phoneUser))
                        {
                            Console.WriteLine("新手机客户登陆记录添加失败：" + phoneNum + timeNow);
                        }
                    }                       
                }

                return tempData;
            }
            catch (Exception ex)
            {
                LogService.WriteLog("PhoneUserRegister2:"+ex.Message);
                return new byte[]{0};
            }
           
        }


        public byte[] IPhoneUserRegister(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);
            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            List<byte> body = new List<byte>();
            try
            {
                string asServerip = "0.0.0.0";
                IPAddress ip = null;
                bool isIpstr = Regex.IsMatch(asServerip, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
                if (isIpstr)
                {
                    ip = IPAddress.Parse(asServerip);
                }
                else
                {
                    IPAddress[] ips = Dns.GetHostAddresses(asServerip);
                    if (ips.Length > 0)
                        ip = ips[0];
                }
                if (ip == null)
                {
                    body.Clear();
                    body.Add(0);
                }
                else
                {
                    body.Add(1);
                    body.AddRange(ip.GetAddressBytes());
                    string phonestr = OperateConfig.GetCenterPhoneNumber();
                    byte[] phoneBcd = CommonRoutine.BcdStringToBytes(phonestr.PadLeft(12, '0'));
                    body.AddRange(phoneBcd);

                    //longitude 
                    string longitudestr = OperateConfig.GetOffSetLongitude();
                    byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                    body.AddRange(longitudeBytes);
                    //latitude 
                    string latitudestr = OperateConfig.GetOffSetLatitude();
                    byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                    body.AddRange(latitudeBytes);


                    //-------占时屏蔽回复Iphone版本号的功能
                    //string version = OperateConfig.GetPhoneUserClientVersion();
                    //byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                    //body.AddRange(vBytes);

                }

                //------------------黑名单               
              
                int count = operateDataBase.GetRecordCountOfUserInThisMonth(phoneNumber, 1);
                if (count >= 1)
                {
                    body.Clear();
                    body.Add(1);
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("PhoneUserProtocol.cs-329");
                body.Clear();
                body.Add(0);
            }
            try
            {
                byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdIPhoneUserRegisterReply, false, false, body.Count, phoneNumberbyts,
                                               serialNumber, 0, 0);
                byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());


                //------------------------将手机用户登陆录入数据库
                DateTime timeNow = DateTime.Now;
                //0-7  IMEI 8byte
                byte[] UDID_bytes = new byte[40];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, UDID_bytes, 0, 40);
                string UDID = Encoding.GetEncoding("UTF-8").GetString(UDID_bytes);

                int bodylength = OperateAgreement.GetMessageLengthInMessageHead(realData);
                //8-11  4byte  Version
                byte[] version_bytes = new byte[bodylength - 40];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex + 40, version_bytes, 0, bodylength - 40);

                string nowVersion = Encoding.GetEncoding("UTF-8").GetString(version_bytes);

                PhoneUserInfo model = operateDataBase.PhoneuserGetModelByPhoneNumber(phoneNumber);
                if (model != null)
                {
                    model.LastLoginTime = timeNow.ToString("yyyy-MM-dd HH:mm:ss");
                    model.PhoneVersion = nowVersion.ToString();
                    model.type = "1";
                    model.LoginCount++;
                    if (string.IsNullOrEmpty(model.PhoneIMEI) &&
                        !operateDataBase.PhoneUserImeiExit(UDID))
                    {
                        model.PhoneIMEI = UDID;
                    }
                    if (!operateDataBase.PhoneuserUpdate(model))
                    {
                        Console.WriteLine("手机客户登陆记录更新失败：" + phoneNumber + timeNow);
                    }
                }
                else  //数据库无记录  增加新用户
                {
                    PhoneUserInfo phoneUser = new PhoneUserInfo();
                    phoneUser.PhoneNumber = phoneNumber;
                    phoneUser.FirstLoginTime = timeNow.ToString("yyyy-MM-dd HH:mm:ss");
                    phoneUser.LastLoginTime = phoneUser.FirstLoginTime;
                    phoneUser.LoginCount = 1;
                    phoneUser.type = "1";
                    phoneUser.PhoneVersion = nowVersion.ToString();

                    // if(!operateDataBase.PhoneUserImeiExit(UDID))
                    {
                        phoneUser.PhoneIMEI = UDID;
                        if (!operateDataBase.PhoneuserAdd(phoneUser))
                        {
                            Console.WriteLine("新手机客户登陆记录添加失败：" + phoneNumber + timeNow);
                        }
                    }
                    //if (!operateDataBase.PhoneuserUpdateByIMEI(IMEI, nowVersion.ToString(), timeNow.ToString("yyyy-MM-dd HH:mm:ss")))
                    //{
                    //    Console.WriteLine("手机用户登陆记录更新失败：" + phoneNum + IMEI + timeNow);
                    //}
                }

                return tempData;
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("IPhoneRegister"+ex.Message);
                return new byte[] { 0 };
            }
             
        }


        public byte[] RecordRegisterCode(byte[] realData)
        {
            int length = OperateAgreement.GetMessageLengthInMessageHead(realData);
            string code = Encoding.GetEncoding("GBK").GetString(realData, ConstParameters.MBodySatrtIndex, length);
            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            if (operateDataBase.PhoneuserUpdateRecommender(phoneNumber, code))
            {
                Console.WriteLine("手机用户推荐人更新成功：" + phoneNumber + DateTime.Now);
            }
            else
            {
                Console.WriteLine("手机用户推荐人更新失败：" + phoneNumber + DateTime.Now);
            }
            //LogService.RecordRegisterCode(code);

            return OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdPhoneUserUpdataRegisterCodeReply);
        }


        public byte[] UserGrade(byte[] realData)
        {
            byte[] phonenumberbytes = new byte[6];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, phonenumberbytes, 0, 6);
            string phoneNumber = CommonRoutine.ByteToBcdString(phonenumberbytes).Substring(1);
            int starLevel = realData[ConstParameters.MBodySatrtIndex + 6];
            if (operateDataBase.TaxiUpdateStarLevel(starLevel, phoneNumber))
            {
                Console.WriteLine("出租车评分更新成功：" + phoneNumber + starLevel + DateTime.Now);
            }
            else
            {
                Console.WriteLine("出租车评分更新失败：" + phoneNumber + starLevel + DateTime.Now);
            }

            return OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdPhoneUserGradeRely);

        }


        public void PhoneUpdataLog(byte[] realData)
        {
            int Length = OperateAgreement.GetMessageLengthInMessageHead(realData);
            string log = Encoding.GetEncoding("GBK").GetString(realData, ConstParameters.MBodySatrtIndex, Length);
            LogService.WritePhoneLog(log, DateTime.Now);
        }

        public byte[] PhoneUserRegistRequest(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            Random ram = new Random();
            int intRandom = ram.Next(0, 999999);
            string strRandom = intRandom.ToString("000000");
            AcceptMainForm.PrivateCarRegistCodeList[phoneNumber] =
            strRandom + "|" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
             

            //发短信phoneNumber 
            string smsContent = "感谢您注册招车王用户,您的验证码为【";
            smsContent += intRandom.ToString("000000");
            smsContent += "】,请在限定时间内在软件中输入该验证码！";
            string result = UnicomSMS.SendSMS(phoneNumber, smsContent);
            byte resultByte = 0;
            if (result.Contains("发送短信成功"))
            {
                resultByte = 1;
            }
            byte body = resultByte;
            byte[] head = OperateAgreement.GetMessageHead(
                ConstParameters.CmdPhoneUserRegistRequestReply,
                false, false, 1, phoneNumberbyts, serialNumber, 0, 0);
            List<byte> message = new List<byte>();
            message.AddRange(head);
            message.Add(body);
            return message.ToArray();
        }


        public byte[] PhoneUserVerifyRegistCode(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
       
            //从消息体中取出验证码 0-3
            byte[] registCodeBytes = new byte[3];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, registCodeBytes, 0, 3);
            string registcode = CommonRoutine.ByteToBcdString(registCodeBytes);
   
            List<byte> body = new List<byte>();
            if (operateDataBase.PhoneuserExists(phoneNumber))
            {
                body.Add(5);//该号码已注册
            }
            else
            {
                if (AcceptMainForm.PrivateCarRegistCodeList.Contains(phoneNumber) ||
                        registcode == DateTime.Now.AddDays(1).ToString("yyMMdd")
                        || registcode == "010203")
                {
                    string[] verifyInfo = null;
                    if (AcceptMainForm.PrivateCarRegistCodeList.Contains(phoneNumber))
                    {
                        string value = AcceptMainForm.PrivateCarRegistCodeList
                        [phoneNumber].ToString();
                        verifyInfo = value.Split('|');
                    }

                    if ((verifyInfo != null && verifyInfo[0] == registcode)
                        || registcode == DateTime.Now.AddDays(1).ToString("yyMMdd")
                        || registcode == "010203")
                    {
                        TimeSpan span = new TimeSpan();
                        if (verifyInfo != null)
                        {
                            span = DateTime.Now - DateTime.Parse(verifyInfo[1]);
                        }

                        if (verifyInfo != null && span.Seconds > 100)
                        {
                            body.Add(2);    //表示验证码正确但已超时                                                  
                        }
                        else//验证成功
                        {                           
                            body.Add(1); //表示注册成功  可尝试登录                               
                        }
                    }
                    else
                    {
                        body.Add(3);//表示验证码错误
                    }
                }
                else
                {
                    body.Add(4);//表示该号码未请求过注册
                }
            }

            byte[] messageHead = OperateAgreement.GetMessageHead(
                ConstParameters.CmdPhoneUserVerifyRegistCodeReply, 
                false, false, body.Count, new byte[6],new byte[2], 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;
        }


        public byte[] PasseagerWantToCarCar(byte[] realData,IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

            //cartype  -1byte
            byte cartype = realData[ConstParameters.MBodySatrtIndex];
       
            //lng  -5byte
            byte[] temp = new byte[5];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex+1, temp, 0, 5);
            double lng = double.Parse(CommonRoutine.ByteToBcdString(temp)) / 1000000;
            //lat -5byte
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 6, temp, 0, 5);
            double lat = double.Parse(CommonRoutine.ByteToBcdString(temp)) / 1000000;

            AcceptMainForm.PositionService.PassengerUpdateInfo(
              phoneNumber, lat,lng,clientIp,cartype);
            byte[] tempData = OperateAgreement.GetEmptyBodyMessageData(
                ConstParameters.CmdPasseagerCallCarReply, phoneNumber);
            return tempData;
        }

    }
}
